package com.rui.study.micro.goods.service.impl;

import com.rui.study.commons.model.BizException;
import com.rui.study.micro.goods.mapper.GoodsMapper;
import com.rui.study.micro.goods.model.GoodsDTO;
import com.rui.study.micro.goods.model.GoodsPo;
import com.rui.study.micro.goods.service.GoodsService;
import com.rui.study.micro.goods.util.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class GoodsServiceImpl implements GoodsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsServiceImpl.class);

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public int createGoods(GoodsDTO goodsDTO) {

        GoodsPo goodsPo = new GoodsPo();
        BeanUtils.copyProperties(goodsDTO, goodsPo);

        int result = goodsMapper.insertUserInfo(goodsPo);
        if (result <= 0)
            throw new BizException(StatusCode.DATA_INSERT_FAILED);
        LOGGER.info("Succeed to create a new goods [{}]", goodsPo);
        return result;
    }

    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = {Exception.class, BizException.class})
    @Override
    public int modGoodsStock(String goodsId, long count) {
        int result = goodsMapper.updateGoodsStock(goodsId, count);
        if (result <= 0)
            throw new BizException(StatusCode.GOODS_COUNT_DEDUCT_FAILED);
        long stock = goodsMapper.queryGoodsStock(goodsId);
        LOGGER.info("Modified the goods [{}] count [{}], and the stock is [{}]", goodsId, count, stock);
        return result;
    }
}
